package com.hliushi.netty.server.handler;

import com.hliushi.netty.message.GroupJoinResponseMessage;
import com.hliushi.netty.message.GroupQuitRequestMessage;
import com.hliushi.netty.server.session.GroupSession;
import com.hliushi.netty.server.session.GroupSessionFactory;
import com.hliushi.netty.server.session.Session;
import com.hliushi.netty.server.session.SessionFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.List;
import java.util.Set;

/**
 * @author llhuang10
 * @date 2021/10/22 10:59
 */
@ChannelHandler.Sharable
public class GroupQuitRequestMessageHandler extends SimpleChannelInboundHandler<GroupQuitRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GroupQuitRequestMessage msg) throws Exception {
        String groupName = msg.getGroupName();
        String username = msg.getUsername();

        GroupSession groupSession = GroupSessionFactory.getGroupSession();
        Set<String> members = groupSession.getMembers(groupName);

        Session session = SessionFactory.getSession();
        Channel channel = session.getChannel(username);
        if (members.remove(username)) {
            // 退出群聊成功, 给群里每个人发一个消息
            List<Channel> membersChannel = groupSession.getMembersChannel(groupName);
            membersChannel.forEach(ch -> {
                ch.writeAndFlush(new GroupJoinResponseMessage(true, username + "已退出" + groupName));
            });
            channel.writeAndFlush(new GroupJoinResponseMessage(true, "您退出" + groupName));
        } else {
            // 退出失败
            System.out.println("");
        }

    }
}
